#
# This file is part of the kernelstudio package.
#
# (c) 2014-2025 zlin <admin@kernelstudio.com>
#
# For the full copyright and license information, please view the LICENSE file
# that was distributed with this source code.
import datetime
import uuid

from ksai.models.document_labels import DocumentLabelsModelQuery, DocumentLabelsModel
from ksai.persistence.database import db
from ksai.utils.strings import has_text


class DocumentLabelsService:

    @staticmethod
    def find_by_query(query: DocumentLabelsModelQuery) -> DocumentLabelsModelQuery:
        q = DocumentLabelsModel.query.filter(DocumentLabelsModel.deleted_at == None)
        if has_text(query.keyword):
            search = f"%{query.keyword}%"
            q = q.filter(
                db.or_(
                    DocumentLabelsModel.name.ilike(search),
                )
            )
        items = q.paginate(page=query.page, per_page=query.offset, error_out=False)
        query.pagination(items)
        return query

    @staticmethod
    def find_one_by_uuid(uuid_param: str) -> DocumentLabelsModel:
        q = DocumentLabelsModel.query.filter(DocumentLabelsModel.deleted_at == None)
        return q.filter_by(uuid=str(uuid_param)).first()

    @staticmethod
    def save(label: DocumentLabelsModel) -> bool:
        if label.uuid is None:
            label.uuid = str(uuid.uuid4())
        if label.created_at is None:
            label.created_at = datetime.datetime.now()
        if label.updated_at is None:
            label.updated_at = datetime.datetime.now()

        if has_text(label.parent_uuid) and "0" != label.parent_uuid:
            parent = DocumentLabelsService.find_one_by_uuid(label.parent_uuid)
            if parent is None:
                raise ValueError("上级不存在.")
        else:
            label.parent_uuid = "0"

        db.session.add(label)
        db.session.commit()
        return True
